<template>
  <ActionPanel :loading="loading">
    <template v-if="ColumnSet && id">
      <ColumnSet v-model="value" :label="label" :column="column" v-bind="elementProps" @keyup.enter="set" />
    </template>
    <ElEmpty v-if="!id" description="数据不存在" class="full" />
    <ElEmpty v-else-if="!ColumnSet" :description="`列【${column.label}】下的元素【${'column.element默认'}】不存在`" class="full" />
    <template #footer>
      <el-button type="primary" @click="set">设置</el-button>
      <el-button v-if="close" @click="close">关闭</el-button>
    </template>
  </ActionPanel>
</template>
<script setup lang="ts">
  import { ElButton, ElEmpty } from 'element-plus'
  import { closePopupKey } from '@/components/Popup'
  import { ActionPanel } from '@/components/ActionPanel'
  import feedback from "@/utils/feedback"
  import { Unit } from '@/seed-application/types'
  import { inject, onMounted, ref } from 'vue'
  import { getApi, setApi } from '@/seed-application/api'
  import { getProperty, getSetColumnName } from '@/seed-application/utils/SeedUtil'
  import { getElement } from '@/seed-application'
  import { getAction, unitKey } from '@/seed-application'
  import { getColumnAndValidator } from '@/seed-application/utils/SetUtil'
  import { isBoolean } from 'lodash-es'

  const props = defineProps<{actionName: string, seedName?: string, microName?: string, id: string, confirm?: string|boolean}>()
  const action = getAction(props.actionName, props.seedName, props.microName)

  const close = inject<() => void>(closePopupKey, void 0)
  const unit = inject<Unit>(unitKey, void 0)

  const property = getProperty(action.seed, getSetColumnName(action.seed, action))
  console.log('property', property)

  const [column, validator] = getColumnAndValidator(action, property)
  const ColumnSet = getElement(column.type, 'set', action.elements?.[column.name]?.element)
  console.log('ColumnSet==', ColumnSet)

  const value = ref()
  const label = ref()
  let elementProps = { ...(action.elements?.[column.name]?.elementProps || {}), multiple: property.type == 'hasMany' || property.type == 'habtm' }
  
  const loading = ref(false)
  onMounted(async () => {
    if(!props.id) return

    setTimeout(async () => {
      try {
        loading.value = true
        const data = await getApi(action, props.id)
        const type = data.type
        switch(type) {
          case 'column':
            value.value = data.value
            break
          case 'belongsTo':
          case 'hasOne':
            value.value = data.value
            label.value = data.label
            break
          case 'hasMany':
          case 'habtm':
            const values = data.values
            if(values) {
              value.value = Object.keys(values).join(',')
              label.value = Object.values(values).join(',')
            }
            break
          default: console.error('未实现')
        }
      } finally {
        loading.value = false
      }
    }, 0)
  })

  const set = async () => {
    try {
      validator.validate({value: value.value}, async errors => {
        console.log('errors==', errors)
        if(errors && errors.length > 0) {
          feedback.alertError(errors[0].message)
        } else {
          const confirm = props.confirm
          if(confirm) await feedback.confirm(isBoolean(confirm) ? `确定要${action.label}吗?` : confirm)
          loading.value = true
          await setApi(action, props.id, value.value)
          loading.value = false
          unit.refresh?.()
          close?.()
          feedback.msgSuccess(`${action.label}成功`);
        }
      })
    } catch (error) {}
  }
</script>